/*******************************************************************

    Author: Xiao
    Date: 2022/3/29 10:50

*******************************************************************/
package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"mcr/pkg/dao"
	"mcr/pkg/logs"
	"mcr/pkg/utils"
)

type MailReq struct {
	Plat    string `json:"plat" binding:"required"`
	Version int    `json:"version" binding:"required"`
	Email   string `json:"email" binding:"required"`
}

// 发送邮箱验证码
func SendEmailVerify(ctx *gin.Context) {
	mq := MailReq{}
	err := ctx.ShouldBindJSON(&mq)
	if err != nil {
		logs.Log.Errorf("获取参数失败:%s", err)
		ctx.JSON(200, gin.H{
			"code": 400,
			"msg":  "邮箱不合法",
		})
		return
	}
	verify := utils.GetVerifyDigitalCode(6)

	err = dao.SetMailVerify(mq.Email+"("+mq.Plat+")", verify)
	if err != nil {
		logs.Log.Errorf("设置邮箱验证码错误:%s", err)
		ctx.JSON(200, gin.H{
			"code": 500,
			"msg":  fmt.Sprintf("验证码获取失败"),
		})
		return
	}
	err = utils.SendVerifyMail(mq.Email, verify)
	if err != nil {
		logs.Log.Errorf("发送邮箱验证码错误:%s", err)
		ctx.JSON(200, gin.H{
			"code": 500,
			"msg":  "邮箱不合法",
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  "验证码已经发送至你的邮箱(十分钟有效)",
	})
	return
}
